<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title th:text="${pageTitle ?: '同步平台 - 编辑数据库'}">同步平台 - 编辑数据库</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.3/font/bootstrap-icons.css">
    <link rel="stylesheet" th:href="@{/css/style.css}">
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar Navigation -->
            <nav id="sidebar" class="col-md-3 col-lg-2 d-md-block bg-dark sidebar collapse">
                <div class="position-sticky pt-3">
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link" th:href="@{/}">
                                <i class="bi bi-house"></i> 首页
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" th:href="@{/dashboard}">
                                <i class="bi bi-speedometer2"></i> 仪表盘
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" th:href="@{/server}">
                                <i class="bi bi-server"></i> 服务器管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active" th:href="@{/database}">
                                <i class="bi bi-database"></i> 数据库管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" th:href="@{/sync/database}">
                                <i class="bi bi-arrow-left-right"></i> 数据库同步
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" th:href="@{/sync/file}">
                                <i class="bi bi-files"></i> 文件同步
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" th:href="@{/restore}">
                                <i class="bi bi-arrow-counterclockwise"></i> 数据库恢复
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" th:href="@{/task/log}">
                                <i class="bi bi-list-check"></i> 同步日志
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>
            
            <!-- Main Content -->
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2" th:text="${database.id != null ? '编辑数据库' : '添加数据库'}">编辑数据库</h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <a th:href="@{/database}" class="btn btn-sm btn-outline-secondary">
                            <i class="bi bi-arrow-left"></i> 返回列表
                        </a>
                    </div>
                </div>
                
                <!-- Database Form -->
                <div class="card">
                    <div class="card-body">
                        <form id="databaseForm" th:object="${database}">
                            <input type="hidden" th:field="*{id}" />
                            
                            <div class="row mb-3">
                                <div class="col-md-6">
                                    <label for="name" class="form-label">数据库名称</label>
                                    <input type="text" class="form-control" id="name" th:field="*{name}" required>
                                    <div class="form-text">用于在系统中标识此数据库</div>
                                </div>
                                <div class="col-md-6">
                                    <label for="dbType" class="form-label">数据库类型</label>
                                    <select class="form-select" id="dbType" th:field="*{dbType}" required>
                                        <option value="">请选择数据库类型</option>
                                        <option value="MYSQL">MySQL</option>
                                        <option value="POSTGRESQL">PostgreSQL</option>
                                        <option value="ORACLE">Oracle</option>
                                        <option value="SQLSERVER">SQL Server</option>
                                    </select>
                                </div>
                            </div>
                            
                            <div class="row mb-3">
                                <div class="col-md-6">
                                    <label for="serverId" class="form-label">服务器</label>
                                    <select class="form-select" id="serverId" th:field="*{serverId}">
                                        <option value="">不关联服务器</option>
                                        <option th:each="server : ${servers}" 
                                                th:value="${server.id}" 
                                                th:text="${server.name + ' (' + server.host + ')'}">
                                            服务器1 (192.168.1.100)
                                        </option>
                                    </select>
                                    <div class="form-text">可以关联到已配置的服务器，或留空使用独立连接</div>
                                </div>
                                <div class="col-md-6">
                                    <label for="host" class="form-label">主机地址</label>
                                    <input type="text" class="form-control" id="host" th:field="*{host}" required>
                                    <div class="form-text" id="hostHelp">数据库服务器的IP地址或域名</div>
                                </div>
                            </div>
                            
                            <div class="row mb-3">
                                <div class="col-md-4">
                                    <label for="port" class="form-label">端口</label>
                                    <input type="number" class="form-control" id="port" th:field="*{port}" required>
                                </div>
                                <div class="col-md-4">
                                    <label for="username" class="form-label">用户名</label>
                                    <input type="text" class="form-control" id="username" th:field="*{username}" required>
                                </div>
                                <div class="col-md-4">
                                    <label for="password" class="form-label">密码</label>
                                    <input type="password" class="form-control" id="password" th:field="*{password}" required>
                                </div>
                            </div>
                            
                            <div class="row mb-3">
                                <div class="col-md-6">
                                    <label for="databaseName" class="form-label">数据库名称</label>
                                    <input type="text" class="form-control" id="databaseName" th:field="*{databaseName}" required>
                                    <div class="form-text">在数据库服务器上的实际数据库名称</div>
                                </div>
                                <div class="col-md-6">
                                    <label for="charset" class="form-label">字符集</label>
                                    <input type="text" class="form-control" id="charset" th:field="*{charset}" placeholder="utf8mb4" value="utf8mb4">
                                </div>
                            </div>
                            
                            <div class="mb-3">
                                <label for="description" class="form-label">描述</label>
                                <textarea class="form-control" id="description" th:field="*{description}" rows="3"></textarea>
                            </div>
                            
                            <div class="d-flex justify-content-between">
                                <div>
                                    <button type="button" id="testConnectionBtn" class="btn btn-info">
                                        <i class="bi bi-check-circle"></i> 测试连接
                                    </button>
                                </div>
                                <div>
                                    <a th:href="@{/database}" class="btn btn-secondary">取消</a>
                                    <button type="button" id="saveBtn" class="btn btn-primary">
                                        <i class="bi bi-save"></i> 保存
                                    </button>
                                </div>
                            </div>
                        </form>
                        
                        <!-- Connection Test Result -->
                        <div id="connectionTestResult" class="mt-3"></div>
                    </div>
                </div>
            </main>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.3/dist/jquery.min.js"></script>
    <script th:src="@{/js/script.js}"></script>
    
    <script th:inline="javascript">
        $(document).ready(function() {
            // Get context path from Thymeleaf
            const contextPath = /*[[@{/}]]*/ '';
            
            // Update port based on database type
            $('#dbType').on('change', function() {
                const dbType = $(this).val();
                let defaultPort = 3306; // MySQL default
                
                switch(dbType) {
                    case 'MYSQL':
                        defaultPort = 3306;
                        break;
                    case 'POSTGRESQL':
                        defaultPort = 5432;
                        break;
                    case 'ORACLE':
                        defaultPort = 1521;
                        break;
                    case 'SQLSERVER':
                        defaultPort = 1433;
                        break;
                }
                
                if (!$('#port').val()) {
                    $('#port').val(defaultPort);
                }
            });
            
            // Update host if server is selected
            $('#serverId').on('change', function() {
                const serverId = $(this).val();
                if (serverId) {
                    // This would ideally fetch the server details and update the host
                    // For simplicity, we're just showing a message
                    $('#hostHelp').text('使用关联服务器的连接信息');
                } else {
                    $('#hostHelp').text('数据库服务器的IP地址或域名');
                }
            });
            
            // Save database
            $('#saveBtn').on('click', function() {
                // Form validation
                if (!$('#databaseForm')[0].checkValidity()) {
                    $('#databaseForm')[0].reportValidity();
                    return;
                }
                
                // Get form data as JSON
                const formData = {
                    id: $('#id').val(),
                    name: $('#name').val(),
                    dbType: $('#dbType').val(),
                    serverId: $('#serverId').val(),
                    host: $('#host').val(),
                    port: parseInt($('#port').val()),
                    username: $('#username').val(),
                    password: $('#password').val(),
                    databaseName: $('#databaseName').val(),
                    charset: $('#charset').val(),
                    description: $('#description').val()
                };
                
                $.ajax({
                    url: contextPath + 'database/save',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(formData),
                    success: function(response) {
                        if (response.success) {
                            window.location.href = contextPath + 'database';
                        } else {
                            alert('保存失败: ' + response.message);
                        }
                    },
                    error: function() {
                        alert('请求失败，请稍后再试。');
                    }
                });
            });
            
            // Test connection
            $('#testConnectionBtn').on('click', function() {
                // Form validation for required fields
                const requiredFields = ['dbType', 'host', 'port', 'username', 'password', 'databaseName'];
                let isValid = true;
                
                requiredFields.forEach(field => {
                    if (!$('#' + field).val()) {
                        isValid = false;
                        $('#' + field).addClass('is-invalid');
                    } else {
                        $('#' + field).removeClass('is-invalid');
                    }
                });
                
                if (!isValid) {
                    alert('请填写所有必填字段');
                    return;
                }
                
                // Get form data as JSON
                const formData = {
                    id: $('#id').val(),
                    dbType: $('#dbType').val(),
                    serverId: $('#serverId').val(),
                    host: $('#host').val(),
                    port: parseInt($('#port').val()),
                    username: $('#username').val(),
                    password: $('#password').val(),
                    databaseName: $('#databaseName').val(),
                    charset: $('#charset').val()
                };
                
                $('#connectionTestResult').html('<div class="spinner-border text-primary" role="status"><span class="visually-hidden">Loading...</span></div>');
                
                $.ajax({
                    url: contextPath + 'database/test',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(formData),
                    success: function(response) {
                        if (response.success) {
                            $('#connectionTestResult').html('<div class="alert alert-success">连接成功!</div>');
                        } else {
                            $('#connectionTestResult').html('<div class="alert alert-danger">连接失败: ' + response.message + '</div>');
                        }
                    },
                    error: function(xhr, status, error) {
                        $('#connectionTestResult').html('<div class="alert alert-danger">请求失败，请稍后再试。错误: ' + status + ' ' + error + '</div>');
                        console.error(xhr.responseText);
                    }
                });
            });
        });
    </script>
</body>
</html> 